package com.curry.android.core;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

import com.curry.android.util.JSONHelper;
@Deprecated
public class CoreHelper {

	private static final int RETRY_TIME = 1000;
	private static final int TIMEOUT_CONNECTION = 30000;
	private static final String TAG = "CoreHelper";

	/**
	 * 公用post方法(json格式提交)
	 * 
	 * @param url
	 * @param serviceId
	 * @param params
	 * @return
	 */
	public static String _post(final String url, final String serviceId,
			final String params,String accesToken) {

		HttpResponse httpResponse = null;

		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("charset", "utf-8");
		httpPost.addHeader("Content-Type", "application/json");

		String responseBody = "";
		int time = 0;
		do {
			try {
				org.apache.http.params.BasicHttpParams httpParams = new org.apache.http.params.BasicHttpParams();
				httpParams.setParameter("charset", "utf-8");
				HttpConnectionParams.setConnectionTimeout(httpParams,
						TIMEOUT_CONNECTION);
				HttpConnectionParams.setSoTimeout(httpParams,
						TIMEOUT_CONNECTION);

				org.apache.http.client.HttpClient httpclient = new DefaultHttpClient(
						httpParams);
				String result = "{\"method\":\"" + serviceId + "\",\"param\":"
						+ params + "}";
				Log.e("result", result);
				StringEntity s = new StringEntity(result, "utf-8");
				s.setContentType("application/json");
				httpPost.setEntity(s);
				httpPost.addHeader("AccessToken", accesToken);
				httpResponse = httpclient.execute(httpPost);
				int statusCode = httpResponse.getStatusLine().getStatusCode();
				if (statusCode != HttpStatus.SC_OK) {
					Log.e("错误", "statusCode:" + statusCode);
					responseBody="500";
				} else if (statusCode == HttpStatus.SC_OK) {
					responseBody = EntityUtils.toString(httpResponse
							.getEntity());
					System.out.println("serviceId========>" + serviceId);
					System.out.println("Json DATA=====>" + responseBody);
				}
				break;
			} catch (Exception e) {
				time++;
				if (time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
					}
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				System.out.println("发生致命的异常，可能是协议不对或者返回的内容有问题");
				e.printStackTrace();
			} finally {
				// 释放连接
				// httpPost.releaseConnection();
				httpPost.abort();
			}
		} while (time < RETRY_TIME);

		return responseBody;
	}

	/**
	 * {"returnMsg":"操作成功", "returnCode":"0",
	 * "returnParams":{"list":{"STAFFID":"AAAM7TAAHAAAIwgAA1"
	 * ,"USERNAME":"lc","NAME":"lc11","USERSTATE":"0"},"total":"1"}}
	 */

	/**
	 * json访问
	 * 
	 */
	public static String _post(final String uri, String header) {
		String result = "";
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(uri);
			httpPost.addHeader("AccessToken", header);
			HttpResponse httpResponse = httpClient.execute(httpPost);

			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(httpResponse.getEntity());
				Log.i("opst", result);
			} else {
				result = "500";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * json访问
	 * 
	 */
	public static String _get(final String uri, String header) {
		Log.e(TAG, "_GET");
		String result = "";
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(uri);
			httpGet.addHeader("AccessToken", header);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			Log.e(TAG, "execute");
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = httpResponse.getEntity();
				result = EntityUtils.toString(entity);
				Log.i(TAG, "result=" + result);
			} else {
				result = "500";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * json访问
	 * 
	 */

	public static String _get(final String uri) {

		String result = "";
		try {
			URL url = new URL(uri);
			HttpURLConnection httpConn = (HttpURLConnection) url
					.openConnection();
			InputStreamReader input = new InputStreamReader(
					httpConn.getInputStream(), "utf-8");
			BufferedReader bufReader = new BufferedReader(input);
			String line = "";
			StringBuilder contentBuf = new StringBuilder();
			while ((line = bufReader.readLine()) != null) {
				contentBuf.append(line);
			}
			result = contentBuf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 获取返回的returnMsg
	 * 
	 * @param josnStr
	 * @return
	 */
	public static String getReturnMsg(String josnStr) {
		Map<String, Object> map = JSONHelper.jsonToMap(josnStr);
		return map.get("returnMsg").toString();
	}

	/**
	 * 获取返回的returnCode
	 * 
	 * @param josnStr
	 * @return
	 */
	public static String getReturnCode(String josnStr) {
		Map<String, Object> map = JSONHelper.jsonToMap(josnStr);
		return map.get("returnCode").toString();
	}

	/**
	 * 获取返回的returnParams
	 * 
	 * @param josnStr
	 * @return
	 */
	public static HashMap<String, Object> getReturnParams(String josnStr) {
		Map<String, Object> map = JSONHelper.jsonToMap(josnStr);
		String returnParams = map.get("returnParams").toString();
		HashMap<String, Object> hashMap = (HashMap<String, Object>) JSONHelper
				.jsonToMap(returnParams);
		return hashMap;
	}

	/**
	 * 获取返回的returnParams中的list数据
	 * 
	 * @param josnStr
	 * @return
	 */
	public static HashMap<String, Object> getReturnParamsList(String josnStr) {
		HashMap<String, Object> returnParams = getReturnParams(josnStr);
		HashMap<String, Object> list = (HashMap<String, Object>) JSONHelper
				.jsonToMap(returnParams.get("list").toString());
		return list;
	}

	// /**
	// * 获取返回的returnParams中的List<Map<String, String>> datalist数据
	// * @param josnStr
	// * @return
	// */
	// public static Object getReturnParamsStr(String josnStr){
	// Map<String, Object> map = JSONHelper.jsonToMap(josnStr);
	// HashMap<String, Object> returnParams = (HashMap<String, Object>)
	// JSONHelper.jsonToMap(map.get("returnParams").toString());
	//
	// Object data = returnParams.get("list").toString();
	// List<Map<String, String>> datalist = (List<Map<String, String>>) data;
	// return datalist;
	// }

	/**
	 * 获取返回的returnParams中的total
	 * 
	 * @param josnStr
	 * @return
	 */
	public static String getTotal(String josnStr) {
		HashMap<String, Object> returnParams = getReturnParams(josnStr);
		return returnParams.get("total").toString();
	}

	/**
	 * <p>
	 * 将文件转成base64 字符串
	 * </p>
	 * 
	 * @param path
	 *            文件路径
	 * @return
	 * @throws Exception
	 */
	public static String encodeBase64File(String path) throws Exception {
		// File file = new File(path);
		// FileInputStream inputFile = new FileInputStream(file);
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;// 关闭分配空间
		Bitmap bitmap = BitmapFactory.decodeFile(path, options);// 读取图片

		int be = (int) (options.outHeight / (float) 800);// 按800计算压缩比
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;
		options.inJustDecodeBounds = false;// 打开分配空间
		bitmap = BitmapFactory.decodeFile(path, options);// 读取压缩后图片
		byte[] buffer = SavePicInLocal(bitmap);
		// inputFile.read(buffer);
		// inputFile.close();
		return android.util.Base64.encodeToString(buffer, Base64.DEFAULT);
	}

	private static byte[] SavePicInLocal(Bitmap bitmap) {
		// FileOutputStream fos = null;
		// BufferedOutputStream bos = null;
		ByteArrayOutputStream baos = null; // 字节数组输出流
		try {
			baos = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
			byte[] byteArray = baos.toByteArray();// 字节数组输出流转换成字节数组
			Log.d("TAG", "size!!!:"+byteArray.length);
			return byteArray;
			// File file = new File(PHOTO_DIR, picName);
			// // 将字节数组写入到刚创建的图片文件中
			// fos = new FileOutputStream(file);
			// bos = new BufferedOutputStream(fos);
			// bos.write(byteArray);

		} catch (Exception e) {
			e.printStackTrace();

		}
		return null;
	}
}
